<template>
	<view
		class="row-wrap text-hide"
		:style="{
			'margin-right': -innerMr + 'px',
			'margin-bottom': -innerMb + 'px',
		}"
	>
		<view
			v-for="(el, i) in data"
			:key="el.value"
			class="rounded-n border py-1 text-center"
			:class="[getThemeClass(el.selected), innerWidth ? '' : 'px-2-2']"
			:style="{
				width: innerWidth ? innerWidth + 'px' : 'auto',
				'margin-right': i === data.length - 1 && !lastHasMr ? 0 : innerMr + 'px',
				'margin-bottom': innerMb + 'px',
				'opacity': disabled ? 0.5 : 1,
			}"
			hover-class="opacity-80"
			hover-start-time="0"
			hover-stay-time="50"
			@click="selectItem(el)"
		>
			<text class="text-xn">{{ el.text }}</text>
		</view>
	</view>
</template>

<script>
import { ref, watch } from 'vue';
import selectableItemsVue from './selectable-items.vue';
export default {
	props: {
		data: Array,
		modelValue: [String, Number, Array],
		mr: {
			type: Number,
			default: 32,
		},
		mb: {
			type: Number,
			default: 0,
		},
		width: {
			type: Number,
			default: 150,
		},
		multiple: Boolean,
		//default white
		type: {
			default: 'default',
			type: String,
		},
		lastHasMr: {
			default: true,
			type: Boolean,
		},
		disabled: Boolean,
	},
	setup(props, ctx) {
		const innerMr = ref(uni.upx2px(props.mr));
		const innerMb = ref(uni.upx2px(props.mb));
		const innerWidth = ref(uni.upx2px(props.width));
		function clearSelected() {
			props.data.forEach((el) => {
				el.selected = false;
			});
		}
		function getSelectedValues() {
			const values = [];
			props.data.forEach((el) => {
				if (el.selected) {
					values.push(el.value);
				}
			});
			return values;
		}
		function selectItem(el) {
			if(props.disabled) return;
			if (props.multiple) {
				el.selected = !el.selected;
				ctx.emit('update:modelValue', getSelectedValues());
			} else {
				if (el.selected) return;
				clearSelected();
				el.selected = true;
				ctx.emit('update:modelValue', el.value);
			}
		}
		function getThemeClass(selected) {
			switch (props.type) {
				case 'white':
					return selected ? 'b-active bg-white color-active' : 'b-color-2 bg-white color-secondary';
			}
			return selected ? 'b-active bg-primary-op10 color-active' : 'b-color-2 bg-b-color-2 color-secondary';
		}
		watch(
			() => props.modelValue,
			(v) => {
				clearSelected();
				if (props.multiple) {
					props.data.forEach((el) => {
						if (v.includes(el.value)) {
							el.selected = true;
						}
					});
				} else {
					const item = props.data.find((el) => el.value === v);
					if (item) {
						item.selected = true;
					}
				}
			},
			{
				immediate: true,
			}
		);
		watch(() => props.data, (data) => {
			data.forEach((el) => {
				if (props.multiple) {
					el.selected = props.modelValue.includes(el.value);
				}else{
					el.selected = el.value === props.modelValue;
				}
			});
		});
		return {
			innerMr,
			innerMb,
			innerWidth,
			selectItem,
			getThemeClass,
		};
	},
};
</script>

<style></style>
